<template>
  <div class="container">
    <!-- 头部导航 -->
    <layoutHeader
      @handlePreview="handlePreview"
      @handleSave="handleSave"
    ></layoutHeader>
    <!-- 主内容区域 -->
    <div class="layout-body">
      <!-- 菜单栏 -->
      <div class="layout-aside">
        <menuList
          :setActiveMenu="activeMenu"
          @changeMenu="changeMenu"
        ></menuList>
      </div>
      <!-- 内容 -->
      <div
        class="layout-content"
        @click.self="
          showControl = false;
          editComIndex = -1;
        "
      >
        <!-- 左侧菜单选择区 -->
        <div
          class="content-left"
          :class="showLeftSide ? 'animateLeftIn' : 'animateLeftOut'"
        >
          <!-- 组件模块 -->
          <moduleContent
            v-if="currentMenu.type == 'module'"
            @addModule="addModule"
          ></moduleContent>
          <!-- 商城页面 -->
          <pageContent
            ref="pageContent"
            v-if="currentMenu.type == 'page'"
            :pageList="pageList"
            :systemPages="systemPages"
            @addPage="addPage"
            @setIndexPage="setIndexPage"
            @deletePage="deletePage"
            @copyPage="copyPage"
            @editPage="editPage"
            @changePage="changePage"
          ></pageContent>
          <!-- 页面控件 -->
          <widgetContent
            v-if="currentMenu.type == 'widget'"
            @editWidget="editWidget"
            :widgetList="controlInitData"
          ></widgetContent>
          <!-- 在线模板 -->
          <templateContent
            v-if="currentMenu.type == 'template'"
          ></templateContent>
        </div>

        <!-- 预览 -->
        <!-- 使用动态组件列表渲染预览选中的组件 -->
        <div
          class="preview-section"
          ref="previewSection"
          @dragover.prevent
          @drop="dropToPreview($event)"
          @click.stop="handlePreviewSection"
        >
          <div :style="pageBgCss" class="test-bg"></div>
          <div
            class="preview-box"
            :class="hasFootNav ? 'add-nav-padding' : ''"
            ref="previewBox"
          >
            <div
              class="component-item"
              :class="!isDraggable ? 'no-drag' : ''"
              v-for="(item, index) in currentPage.templates"
              :key="index"
              @click.stop="clickCom(item, index)"
              @mouseenter="showComControl = index"
              @mouseleave="showComControl = -1"
              v-dragging="{
                item: item,
                list: currentPage.templates,
                group: 'item',
              }"
            >
              <!-- 组件编辑悬浮框 -->
              <a-tooltip>
                <comControl
                  v-if="
                    showComControl == index &&
                    currentPage.system_type != 'cart' &&
                    item.controlComName
                  "
                  :comIndex="index"
                  :comItem="item"
                  :templateLength="currentPage.templates.length"
                  :templates="currentPage.templates"
                  @gotoEditCom="gotoEditCom"
                  @changeComPosition="changeComPosition"
                  @deleteCom="deleteCom"
                ></comControl>
              </a-tooltip>
              <!-- 组件选中 -->
              <div
                class="com"
                :class="
                  (showComControl == index || editComIndex == index) &&
                  currentPage.system_type != 'cart' &&
                  item.controlComName
                    ? 'hover-com'
                    : ''
                "
              >
                <component
                  :is="item.comName"
                  :propsData="item"
                  @chooseMoudle="
                    (e) => {
                      clickCom(e, index);
                    }
                  "
                ></component>
              </div>
            </div>
            <!-- 没有配置内容时显示 -->
            <previewDefault
              v-if="
                !currentPage.templates ||
                currentPage.templates.length == 0 ||
                !pageList.length
              "
              @gotoAddModule="gotoAddModule"
            ></previewDefault>
          </div>

          <!-- 控件列表 -->
          <widgetList
            :widgetList="controlInitData"
            :pageList="pageList"
            :systemPages="systemPages"
            @chooseMoudle="editWidget"
            @changePage="changePage"
          ></widgetList>

          <SlideTree
            :navList="currentComponent.params.list"
            @change="
              (e) => {
                currentComponent.params.list = e;
              }
            "
            :type="currentComponent.comName"
            v-if="
              (currentComponent.comName == 'cubeNav' ||
                currentComponent.comName == 'userTools') &&
              showControl
            "
          ></SlideTree>
        </div>

        <!-- 预览侧边栏编辑组件 -->
        <asideControl
          @handlePageSet="handlePageSet"
          @handleAsideSave="handleAsideSave"
          @handleTheme="handleTheme"
          @handleAsideCancel="handleAsideCancel"
        ></asideControl>

        <!-- 内容编辑区域 -->
        <div
          class="content-control"
          :class="showControl ? 'animateRightIn' : 'animateRightOut'"
        >
          <div class="control-section">
            <div class="section-body">
              <component
                v-if="showControl"
                :is="currentComponent.controlComName"
                :params="currentComponent"
              ></component>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 菜单组件
import layoutHeader from "@/components/DiyNew/layoutHeader/index.vue";
import menuList from "@/components/DiyNew/menu/menuList.vue";
import moduleContent from "@/components/DiyNew/menu/module/index.vue";
import pageContent from "@/components/DiyNew/menu/page/index.vue";
import widgetContent from "@/components/DiyNew/menu/widget/index.vue";
import templateContent from "@/components/DiyNew/menu/template/index.vue";

import widgetList from "@/components/DiyNew/diy/widget/index.vue"; // 控件预览组件 

// 预览侧边栏编辑组件
import asideControl from "@/components/DiyNew/asideControl/index.vue";

// diy组件
import { DiyComponents } from "@/components/DiyNew/diy/index.js";

// 默认diy数据
import { Diys } from "@/components/DiyNew/diy/dataConfig/config.js";

import {
  pageInitData,
  controlInitData,
  mockSystemPage,
} from "@/components/DiyNew/diy/dataConfig/pageConfig.js";

// diy接口
import {
  templateList,
  getDiySysTemPages,
  createDiyPage,
  saveDiyPage,
  deleteDiyPage,
  setDiyIndexPage,
  saveDiySysTemPage,
} from "@/api/diy/diy";

import Vue from "vue";
import { setWithAction } from "@/utils/prototypes.js";

export default {
  name: "App",
  components: {
    layoutHeader,
    menuList,
    moduleContent,
    pageContent,
    widgetContent,
    templateContent,
    asideControl,
    widgetList,
    ...DiyComponents,
  },
  data() {
    return {
      currentMenu: {
        icon: "icon-zuocecaidan-mokuai",
        text: "模块",
        type: "module",
        comName: "module",
      }, // 当前菜单

      showControl: false, // 展示右侧编辑模块
      showLeftSide: false, // 展示左侧菜单内属性

      currentComponent: {}, // 当前编辑的组件

      pageList: [], // 页面列表
      activeMenu: "", // 指定active的菜单
      currentWidget: "", // 当前页面控件
      showComControl: -1, // 组件编辑悬浮组件是否展示
      controlInitData: controlInitData,
      pageWidget: null, // 页面控件
      store_id: "-1",
      editComIndex: -1,
      systemPages: [], // diy系统页面列表
      showWidgetEditHover: false,
    };
  },
  mounted() {
    // if (getUrlParam("store_id")) this.store_id = getUrlParam("store_id");
    this.getDiyTemplates();
    this.getDiySysTemPages();
    this.$dragging.$on("dragged", ({ value }) => {
      console.log("拖拽===", value);
    });
    this.$dragging.$on("dragend", ({ value }) => {
      console.log("拖拽结束", value);
      console.log("模板数组：", this.currentPage.templates);
      console.log("页面数据：", this.$diyObser.store.currentPage);
    });

    // 获取预览盒子的节点，以便于后续方便设置滚动(diy搜索组件固顶用到了)
    this.$diyObser.mutations.setRef(this.$refs.previewBox);

    // 设置原型set方法，方便撤销操作
    Vue.prototype.$setWithAction = setWithAction;

    this.$eventHub.$on("setThemeColor", (e) => {
      this.controlInitData.forEach((d) => {
        if (d.name == "导航") {
          d.params.activeColor = e.color;
        }
      });
      let templates = JSON.parse(JSON.stringify(this.currentPage.templates));
      templates.forEach((d) => {
        if (d.comName == "productShow" || d.comName == "productClassify") {
          d.params.priceColor = e.color;
        }
      });
      this.$set(this.currentPage, "templates", templates);
    });
  },
  computed: {
    // 当前页面
    currentPage: {
      get() {
        return this.$diyObser.store.currentPage;
      },
      set(val) {
        this.$diyObser.store.currentPage = val;
      },
    },
    actionStep() {
      return this.$diyObser.store.actionStep;
    },
    currentAction() {
      return this.$diyObser.store.currentAction;
    },
    pageBgCss() {
      if (this.currentPage.pageCss) {
        let pageCss = JSON.parse(JSON.stringify(this.currentPage.pageCss));
        if (pageCss?.padding) delete pageCss.padding;
        if (pageCss?.borderRadius) delete pageCss.borderRadius;
        return pageCss;
      } else {
        return "";
      }
    },
    isDraggable() {
      let flag = true;
      if (this.currentPage?.page_type) {
        flag = false;
      }
      return flag;
    },
    hasFootNav() {
      let [list] = this.controlInitData.filter((d) => {
        return d.controlComName == "widgetNavControl";
      });
      let flag = false;
      if (list) {
        let navList = list.params.navList || [];
        if (navList.length && list.is_show) flag = true;
      }
      return flag;
    },
  },
  watch: {},
  methods: {
    /**
     * 获取diy配置数据
     * 该方法返回控件列表及页面列表
     * */

    getDiyTemplates() {
      templateList({
        url: "/diy/new-template-list",
        data: { store_id: this.store_id },
      }).then((res) => {
        if (!res.code && res.data) {
          let data = res.data;
          let arr = [];
          if (data.list.length) {
            data.list.forEach((d) => {
              let item = JSON.parse(d.template);
              item["id"] = d.id;
              item.is_index = d.is_index;
              arr.push(item);
            });
            console.log(arr, data.list);
          }
          this.pageList = arr;
          this.initPage();
          if (!data.controls) {
            this.pageWidget = controlInitData;
          } else {
            this.pageWidget = JSON.parse(data.controls);
            this.controlInitData = JSON.parse(data.controls);
          }
        }
      });
    },
    // 获取系统页面列表
    getDiySysTemPages() {
      getDiySysTemPages({
        url: "/diy/system-template-list",
        data: { store_id: this.store_id },
      }).then((res) => {
        if (!res.code && res.data) {
          let arr = [];
          if (res.data.list.length) {
            res.data.list.forEach((d) => {
              let item = JSON.parse(d.template);
              item["id"] = d.id;
              item.is_index = d.is_index;
              arr.push(item);
            });
          }
          this.systemPages = arr;
          console.log("系统页面=====", this.systemPages);
        }
      });
    },
    // 初始化筛选出首页
    initPage() {
      let [item] = this.pageList.filter((d) => {
        return d.is_index == 1;
      });
      if (item) {
        this.$diyObser.mutations.setCurrentPage(item);
        this.gotoAddModule();
      }
    },
    // 切换菜单回调
    changeMenu(e) {
      console.log(e);
      this.currentMenu = e.menu;
      this.showLeftSide = true;
      this.showControl = false;
      this.activeMenu = "";
      // 切换菜单时，重置页面name属性
      this.$diyObser.mutations.setPageName("");
      this.$diyObser.mutations.setCurrentComponent({});
    },
    // 点击预览中的组件
    clickCom(item, index) {
      if (item.comName == "shoppingCart") {
        return;
      }
      if (!item.controlComName) return;
      console.log("点击组件了", item, index);
      this.currentComponent = item;
      this.showControl = true;
      this.editComIndex = index;
      this.$diyObser.mutations.setCurrentComponent(item);
      this.$diyObser.mutations.setCurrentComIndex(index);
    },
    // 点击编辑组件
    gotoEditCom(e) {
      console.log(e);
      let index = e.index;
      this.currentComponent = this.currentPage.templates[index];
      if (this.showControl) return;
      this.showControl = true;
    },
    // 调换组件位置
    changeComPosition(e) {
      let { type, index } = { ...e };
      console.log(type, index);
      let sIndex = type == "top" ? index - 1 : index + 1;
      this.currentPage.templates.splice(
        index,
        1,
        ...this.currentPage.templates.splice(
          sIndex,
          1,
          this.currentPage.templates[index]
        )
      );
      console.log(this.currentPage.templates);
    },
    // 删除组件
    deleteCom(e) {
      console.log(e.index);
      let index = e.index;
      this.currentPage.templates.splice(index, 1);
    },
    // 开始配置页面
    gotoAddModule() {
      this.activeMenu = "module";
      this.showLeftSide = true;
    },
    // 点击预览
    handlePreview() {
      console.log("预览");
      this.showLeftSide = false;
      this.showControl = false;
    },
    // 点击保存
    handleSave() {
      this.$confirm({
        title: "提示",
        content: "确认保存？",
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          console.log("确认保存");
          console.log(this.pageList);
          this.handleAsideSave();
        },
        onCancel: () => {
          console.log("取消保存");
        },
      });
    },
    // 添加页面
    addPage() {
      let data = JSON.parse(JSON.stringify(pageInitData));
      let obj = {
        template: JSON.stringify(data),
        id: null,
        type: "0",
        is_index: 0,
        controls: JSON.stringify(this.controlInitData),
        store_id: this.store_id,
      };
      createDiyPage({ url: "/diy/new-template-save", data: obj })
        .then((res) => {
          if (!res.code) {
            this.$message.success(res.msg);
            let resData = res.data;
            let page = JSON.parse(resData.template.template);
            page["id"] = resData.template.id;
            this.pageList.push(page);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 设置首页
    setIndexPage(e) {
      let item = e.item;
      if (item.is_index == 1) return;
      setDiyIndexPage({
        data: { id: item.id, store_id: this.store_id, type: "is_index" },
      }).then((res) => {
        if (!res.code) {
          this.pageList.forEach((d) => {
            if (d.id == item.id) {
              d.is_index = 1;
            } else {
              d.is_index = 0;
            }
          });
        }
      });
    },
    // 更新保存页面数据
    requestUpdate(params, cb, noToast = false) {
      params = { store_id: this.store_id, ...params };
      saveDiyPage({ url: "/diy/new-template-save", data: params })
        .then((res) => {
          console.log(res);
          if (!res.code) {
            if (!noToast) {
              this.$message.success(res.msg);
            }
            cb && cb();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 保存系统页面数据
    saveDiySysTemPage(params, cb, noToast = false) {
      params = { store_id: this.store_id, ...params };
      saveDiySysTemPage({ url: "/diy/system-template-save", data: params })
        .then((res) => {
          console.log(res);
          if (!res.code) {
            if (!noToast) {
              this.$message.success(res.msg);
            }
            cb && cb();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 删除页面
    deletePage(e) {
      let item = e.item;
      deleteDiyPage({
        url: "/diy/new-template-del",
        data: { id: item.id, store_id: this.store_id },
      }).then((res) => {
        if (!res.code) {
          let index = this.pageList.findIndex((d) => {
            return d.id == item.id;
          });
          this.pageList.splice(index, 1);
          this.$message.success("删除成功！");
        }
      });
    },
    // 复制页面
    copyPage(e) {
      let item = e.item;
      let data = JSON.parse(JSON.stringify(item));
      data.is_index = 0;
      let obj = {
        template: JSON.stringify(data),
        id: null,
        type: "0",
        controls: JSON.stringify(this.controlInitData),
        is_index: 0,
        store_id: this.store_id,
      };
      createDiyPage({ url: "/diy/new-template-save", data: obj })
        .then((res) => {
          console.log(res);
          if (!res.code) {
            let resData = res.data;
            let page = JSON.parse(resData.template.template);
            page["id"] = resData.template.id;
            this.pageList.push(page);
            this.$message.success(res.msg);

            this.$diyObser.mutations.setCurrentPage(page);
            this.$refs.pageContent.initPage();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 编辑页面
    editPage(e) {
      let item = e.item;
      this.currentPage = item;
      this.$diyObser.mutations.setCurrentPage(item);
      this.showControl = true;
      this.currentComponent = item;
    },
    // 切换页面
    changePage(e) {
      this.showControl = false;
      let data = JSON.parse(JSON.stringify(this.currentPage));

      let obj = {
        template: JSON.stringify(data),
        id: data.id,
        type: data.page_type,
        controls: JSON.stringify(this.controlInitData),
        store_id: this.store_id,
        is_index: data.is_index,
      };
      if (this.currentPage.page_type == 1) {
        this.saveDiySysTemPage(obj, () => {
          this.$diyObser.mutations.setActionStep([]);
          setTimeout(() => {
            this.$diyObser.mutations.setCurrentPage(e.item);
            this.$diyObser.mutations.setActionStep([]);
          }, 0);
        });
        return;
      }
      this.requestUpdate(
        obj,
        () => {
          this.$diyObser.mutations.setActionStep([]);
          setTimeout(() => {
            this.$diyObser.mutations.setCurrentPage(e.item);
            this.$diyObser.mutations.setActionStep([]);
          }, 0);
        },
        true
      );
    },
    // 编辑页面控件
    editWidget(e) {
      console.log("编辑页面控件", e.item);
      if (e.item.controlComName == "widgetNavControl") this.editComIndex = -1;
      this.currentWidget = e.item;
      this.showControl = true;
      this.currentComponent = e.item;
      this.$diyObser.mutations.setCurrentComponent(e.item);
    },
    // 点击快捷按钮回调
    handlePageSet(e) {
      let page = this.$diyObser.store.currentPage;
      this.currentComponent = page;
      this.activeMenu = "page";
      setTimeout(() => {
        this.showControl = true;
      }, 0);
    },
    // 点击撤销
    handleAsideCancel() {
      console.log("撤销操作");
      if (this.actionStep.length <= 0) return;
      console.log("动作数组：", this.actionStep);
      this.showControl = false;
      let length = this.actionStep.length;
      let item = this.actionStep[length - 1];
      console.log("数据===：", item);
      this.currentPage.templates.forEach((d, index) => {
        if (d.comName == item.comName && index == item.index) {
          console.log("旧数据：", item.old);
          this.currentPage.templates.splice(index, 1, item.old);
        }
      });
      setTimeout(() => {
        let arr = this.$diyObser.store.actionStep;
        arr.splice(arr.length - 1, 1);
        this.$diyObser.mutations.setActionStep(arr);
      }, 0);
    },
    // 拖拽元素落入预览区内监听
    dropToPreview(e) {
      console.log("拖拽完，扔我这=====", e);
      console.log("拖拽的按个玩意=", this.$diyObser.store.dragItem);
      let item = this.$diyObser.store.dragItem;
      if (item) {
        let page = this.$diyObser.store.currentPage;
        // 如果页面内没有模块，则先添加页面头部组件进去
        if (!page.templates.length) {
          page.templates.push(Diys.pageHeader);
        }
        let data = JSON.parse(JSON.stringify(item));
        page.templates.push(data);
      }
    },
    // 添加模块
    addModule(e) {
      let item = e.item;
      if (item) {
        let page = this.$diyObser.store.currentPage;
        if (!this.pageList.length) {
          this.$message.error("您还尚未创建页面！");
          return;
        }
        // 如果页面内没有模块，则先添加页面头部组件进去
        if (!page.templates.length) {
          page.templates.push(Diys.pageHeader);
        }
        let data = JSON.parse(JSON.stringify(item));
        page.templates.push(data);
        // 添加模块时，直接展示，该模块对应的编辑组件
        this.editComIndex = page.templates.length - 1;
        this.currentComponent = data;
        this.showControl = true;
        // 添加后滚动至页面底部
        this.$nextTick(() => {
          let container = this.$refs.previewBox;
          container.scrollTop = container.scrollHeight;
        });
      }
    },
    // 点击侧边栏保存
    handleAsideSave() {
      console.log(this.$diyObser.store.currentPage, this.controlInitData);
      let data = JSON.parse(JSON.stringify(this.currentPage));
      console.log(data);
      let obj = {
        template: JSON.stringify(data),
        id: data.id,
        type: data.page_type,
        controls: JSON.stringify(this.controlInitData),
        store_id: this.store_id,
        is_index: data.is_index,
      };
      if (this.currentPage.page_type == 1) {
        this.saveDiySysTemPage(obj);
        return;
      }
      this.requestUpdate(obj);
    },
    // 点击全局配色
    handleTheme(e) {
      console.log(e);
      let item = e.item;
      this.currentComponent = item;
      if (!this.showControl) this.showControl = true;
    },
    // 点击预览区域
    handlePreviewSection() {
      this.activeMenu = "module";
      this.showLeftSide = true;
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height:calc(100vh - 48px);
  display: flex;
  flex-direction: column;

  .layout-body {
    width: 100%;
    flex: 1;
    display: flex;
    justify-content: flex-start;
    .layout-aside {
      width: 50px;
      height: 100%;
      background: #ffffff;
      border-right: 1px solid #f0f2f5;
    }
    .layout-content {
      flex: 1;
      height: 100%;
      background: #f0f2f5;
      position: relative;
      overflow: hidden;

      .content-left {
        width: 328px;
        height: 100%;
        background: #ffffff;
        position: absolute;
        left: -328px;
        bottom: 0;
        transition: all 0.2s;
        overflow-y: auto;
      }
      .content-left::-webkit-scrollbar {
        width: 0px;
      }

      .animateLeftIn {
        left: 0;
      }
      .animateLeftOut {
        left: -328px;
      }

      .preview-section {
        width: 375px;
        height: 667px;
        background-color: #f6f7f9;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
        border-radius: 4px;

        .preview-box {
          width: 100%;
          height: 100%;
          overflow-x: hidden;
          overflow-y: auto;
        }

        .preview-box::-webkit-scrollbar {
          width: 0;
        }

        .add-nav-padding {
          padding-bottom: 50px;
        }

        .test-bg {
          width: 100%;
          height: 100%;
          z-index: -1;
          position: absolute;
          left: 0;
          top: 0;
        }

        .component-item {
          position: relative;
        }
        .no-drag {
          -webkit-user-drag: none;
        }
        .hover-com::before {
          content: "";
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          border: 1px dashed;
          border-color: #000000;
          z-index: 22;
          display: inline-block;
          pointer-events: none;
        }
      }

      .content-control {
        width: 276px;
        height: calc(100vh - 54px - 48px);
        background: #ffffff;
        position: absolute;
        right: -276px;
        bottom: 0;
        transition: all 0.2s;
        .control-section {
          .section-header {
            width: 100%;
            height: 48px;
            background: #ffffff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 24px;
            border-bottom: 1px solid #f0f2f5;
            p {
              margin: 0;
            }
            .header-left {
              font-size: 14px;
              font-weight: 600;
              line-height: 20px;
              color: #000000;
            }
            .header-right {
              font-size: 12px;
              font-weight: 400;
              color: #000000;
              opacity: 0.45;
            }
          }
          .section-body {
            width: 100%;
            height: calc(100vh - 54px);
            overflow-y: scroll;

            ::v-deep .ant-input {
              background-color: #f6f7f9;
            }
            ::v-deep .ant-input:hover {
              background-color: #f2f2f2;
            }

            ::v-deep .ant-select-selection--single {
              background: #f6f7f9;
            }
            ::v-deep .ant-select-selection--single:hover {
              background: #f2f2f2;
            }

            ::v-deep.control-item
              .control-content
              .example-list
              .example-item:hover {
              background-color: #e3e4e6;
            }
          }
          .section-body::-webkit-scrollbar {
            width: 0;
          }
        }
      }

      .animateRightIn {
        right: 0;
      }
      .animateRightOut {
        right: -276px;
      }
    }
  }
}
</style>
